package cycling.taxi.com.ui.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import butterknife.ButterKnife;
import butterknife.InjectView;
import cycling.taxi.com.IConstants;
import cycling.taxi.com.R;
import cycling.taxi.com.person.ExitApplication;
import cycling.taxi.com.request.Config;
import cycling.taxi.com.request.RM;
import cycling.taxi.com.request.RequestBean;
import cycling.taxi.com.request.RequestCallback;
import cycling.taxi.com.request.RequestParams;
import cycling.taxi.com.request.RequestUtil;
import cycling.taxi.com.utils.LogUtil;
import cycling.taxi.com.utils.MD5Util;
import cycling.taxi.com.utils.PhoneUtils;
import cycling.taxi.com.utils.SPUtil;
import cycling.taxi.com.utils.ToastUtil;
import cycling.taxi.com.utils.Urls;
import cycling.taxi.com.zxing.android.CaptureActivity;

/**
 * Created by Administrator on 2017/4/26.
 */
public class RegisterAty extends AppCompatActivity implements View.OnClickListener,RequestCallback{
    private EditText mobile,fancilty;
    private Button validate,register;
    private EditText val,cont_name,pwd1;
    private ImageView back;
    private TextView title_text;
    private Button mForward;
    private TextView mFilterText;
    private RequestQueue queue;
    private Spinner provinceSpinner = null;  //省级（省、直辖市）
    private Spinner citySpinner = null;     //地级市
    private Spinner countySpinner = null;    //县级（区、县、县级市）
    ArrayAdapter<String> provinceAdapter = null;  //省级适配器
    ArrayAdapter<String> cityAdapter = null;    //地级适配器
    ArrayAdapter<String> countyAdapter = null;    //县级适配器
    static int provincePosition = 3;
    private static final String DECODED_CONTENT_KEY = "codedContent";
    private static final String DECODED_BITMAP_KEY = "codedBitmap";
    private static final int REQUEST_CODE_SCAN = 0x0000;
    private String rad="()*";
    //省级选项值
    private String[] province = new String[] {"北京","天津","河北","山西","内蒙古自治区","辽宁","吉林","黑龙江",
            "上海","江苏","浙江","安徽","福建","江西","山东","河南","湖北","湖南","广东","广西壮族自治区",
            "海南","重庆","四川","贵州","云南","西藏自治区","陕西","甘肃","青海","宁夏回族自治区","新疆维吾尔自治区",
            "香港特别行政区","澳门特别行政区","台湾"};//,"重庆","黑龙江","江苏","山东","浙江","香港","澳门"};
    //地级选项值
    private String[][] city = new String[][]
            {
                    { "北京" },
                    { "天津" },
                    { "石家庄", "张家口", "承德", "秦皇岛", "唐山", "廊坊", "保定", "沧州", "衡水", "邢台", "邯郸" },
                    { "太原", "大同", "朔州", "阳泉", "长治", "晋城", "忻州", "吕梁", "晋中", "临汾", "运城"},
                    {"呼和浩特", "包头", "乌海", "赤峰", "呼伦贝尔盟", "兴安盟", "哲里木盟", "锡林郭勒盟", "乌兰察布盟", "鄂尔多斯", "巴彦淖尔盟", "阿拉善盟"},
                    {"沈阳", "朝阳", "阜新", "铁岭", "抚顺", "本溪", "辽阳", "鞍山", "丹东", "大连", "营口", "盘锦", "锦州", "葫芦岛"},
                    {"长春", "白城", "松原", "吉林", "四平", "辽源", "通化", "白山", "延边"},
                    {"哈尔滨", "齐齐哈尔", "黑河", "大庆", "伊春", "鹤岗", "佳木斯", "双鸭山", "七台河", "鸡西", "牡丹江", "绥化", "大兴安"},
                    {"上海"},
                    {"南京", "徐州", "连云港", "宿迁", "淮阴", "盐城", "扬州", "泰州", "南通", "镇江", "常州", "无锡", "苏州"},
                    {"杭州", "湖州", "嘉兴", "舟山", "宁波", "绍兴", "金华", "台州", "温州", "丽水"},
                    {"合肥", "宿州", "淮北", "阜阳", "蚌埠", "淮南", "滁州", "马鞍山", "芜湖", "铜陵", "安庆", "黄山", "六安", "巢湖", "池州", "宣城"},
                    {"福州", "南平", "三明", "莆田", "泉州", "厦门", "漳州", "龙岩", "宁德"},
                    {"南昌", "九江", "景德镇", "鹰潭", "新余", "萍乡", "赣州", "上饶", "抚州", "宜春", "吉安"},
                    {"济南", "聊城", "德州", "东营", "淄博", "潍坊", "烟台", "威海", "青岛", "日照", "临沂", "枣庄", "济宁", "泰安", "莱芜", "滨州", "菏泽"},
                    {"郑州", "三门峡", "洛阳", "焦作", "新乡", "鹤壁", "安阳", "濮阳", "开封", "商丘", "许昌", "漯河", "平顶山", "南阳", "信阳", "周口", "驻马店"},
                    {"武汉", "十堰", "襄攀", "荆门", "孝感", "黄冈", "鄂州", "黄石", "咸宁", "荆州", "宜昌", "恩施", "襄樊"},
                    {"长沙", "张家界", "常德", "益阳", "岳阳", "株洲", "湘潭", "衡阳", "郴州", "永州", "邵阳", "怀化", "娄底", "湘西"},
                    {"广州", "清远", "韶关", "河源", "梅州", "潮州", "汕头", "揭阳", "汕尾", "惠州", "东莞", "深圳", "珠海", "江门", "佛山", "肇庆", "云浮", "阳江", "茂名", "湛江"},
                    {"南宁", "桂林", "柳州", "梧州", "贵港", "玉林", "钦州", "北海", "防城港", "南宁", "百色", "河池", "柳州", "贺州"},
                    {"海口", "三亚"},
                    {"重庆"},
                    {"成都", "广元", "绵阳", "德阳", "南充", "广安", "遂宁", "内江", "乐山", "自贡", "泸州", "宜宾", "攀枝花", "巴中", "达川", "资阳", "眉山", "雅安", "阿坝", "甘孜", "凉山"},
                    {"贵阳", "六盘水", "遵义", "毕节", "铜仁", "安顺", "黔东南", "黔南", "黔西南"},
                    {"昆明", "曲靖", "玉溪", "丽江", "昭通", "思茅", "临沧", "保山", "德宏", "怒江", "迪庆", "大理", "楚雄", "红河", "文山", "西双版纳"},
                    {"拉萨", "那曲", "昌都", "林芝", "山南", "日喀则", "阿里"},
                    {"西安", "延安", "铜川", "渭南", "咸阳", "宝鸡", "汉中", "榆林", "商洛", "安康"},
                    {"兰州", "嘉峪关", "金昌", "白银", "天水", "酒泉", "张掖", "武威", "庆阳", "平凉", "定西", "陇南", "临夏", "甘南"},
                    {"西宁", "海东", "西宁", "海北", "海南", "黄南", "果洛", "玉树", "海西"},
                    {"银川", "石嘴山", "吴忠", "固原"},
                    {"乌鲁木齐", "克拉玛依", "喀什", "阿克苏", "和田", "吐鲁番", "哈密", "博尔塔拉", "昌吉", "巴音郭楞", "伊犁", "塔城", "阿勒泰"},
                    {"香港"},
                    {"澳门"},
                    {"台北","台南","其他"},

            };
   /* //县级选项值
    private String[][][] county = new String[][][]
            {
                    {   //北京
                            {"无"},{"无"},{"无"},{"无"},{"无"},{"无"},{"无"},{"无"},{"无"},{"无"},
                            {"无"},{"无"},{"无"},{"无"},{"无"},{"无"},{"无"},{"无"}
                    },
                    {    //上海
                            {"无"},{"无"},{"无"},{"无"},{"无"}
                    },
                    {    //天津
                            {"无"},{"无"},{"无"},{"无"},{"无"},{"无"},{"无"},{"无"},{"无"},{"无"}
                    },
                    {    //广东
                            {"海珠区","荔湾区","越秀区","白云区","萝岗区","天河区","黄埔区","花都区","从化市","增城市","番禺区","南沙区"}, //广州
                            {"宝安区","福田区","龙岗区","罗湖区","南山区","盐田区"}, //深圳
                            {"武江区","浈江区","曲江区","乐昌市","南雄市","始兴县","仁化县","翁源县","新丰县","乳源县"}  //韶关
                    }
            };*/
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

            initUI();

            initData();

            queue= Volley.newRequestQueue(this);
            setListener();
            setSpinner();


    }
    /*
         * 设置下拉框
         */
    private void setSpinner()
    {
        provinceSpinner = (Spinner)findViewById(R.id.spin_province);
        citySpinner = (Spinner)findViewById(R.id.spin_city);
        //countySpinner = (Spinner)findViewById(R.id.spin_county);

        //绑定适配器和值
        provinceAdapter = new ArrayAdapter<String>(RegisterAty.this,
                android.R.layout.simple_spinner_item, province);
        provinceSpinner.setAdapter(provinceAdapter);
        provinceSpinner.setSelection(0,true);  //设置默认选中项，此处为默认选中第4个值

        cityAdapter = new ArrayAdapter<String>(RegisterAty.this,
                android.R.layout.simple_spinner_item, city[0]);
        citySpinner.setAdapter(cityAdapter);
        citySpinner.setSelection(0,true);  //默认选中第0个

//        countyAdapter = new ArrayAdapter<String>(RegisterAty.this,
//                android.R.layout.simple_spinner_item, county[3][0]);
//        countySpinner.setAdapter(countyAdapter);
//        countySpinner.setSelection(0, true);


        //省级下拉框监听
        provinceSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
        {

            // 表示选项被改变的时候触发此方法，主要实现办法：动态改变地级适配器的绑定值
            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long arg3)
            {
                //position为当前省级选中的值的序号

                //将地级适配器的值改变为city[position]中的值
                cityAdapter = new ArrayAdapter<String>(
                        RegisterAty.this, android.R.layout.simple_spinner_item, city[position]);
                // 设置二级下拉列表的选项内容适配器
                citySpinner.setAdapter(cityAdapter);
                provincePosition = position;    //记录当前省级序号，留给下面修改县级适配器时用
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0)
            {

            }

        });


//        //地级下拉监听
//        citySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
//        {
//
//            @Override
//            public void onItemSelected(AdapterView<?> arg0, View arg1,
//                                       int position, long arg3)
//            {
//                countyAdapter = new ArrayAdapter<String>(RegisterAty.this,
//                        android.R.layout.simple_spinner_item);
//                countySpinner.setAdapter(countyAdapter);
//            }
//
//            @Override
//            public void onNothingSelected(AdapterView<?> arg0)
//            {
//
//            }
//        });
    }

    private void setListener() {
        validate.setOnClickListener(this);
        register.setOnClickListener(this);
        back.setOnClickListener(this);
        mForward.setOnClickListener(this);

    }

    private void initData() {

    }

    private void initUI() {
        setContentView(R.layout.activity_register);
        ExitApplication.getInstance().addActivity(this);
        mobile= (EditText) findViewById(R.id.mobile);
        validate= (Button) findViewById(R.id.validate);
        register= (Button) findViewById(R.id.register);
        fancilty=(EditText)findViewById(R.id.bindfancility);
        mFilterText=(TextView) findViewById(R.id.filter_text);
        mForward=(Button) findViewById(R.id.forward);
        val= (EditText) findViewById(R.id.val);
        cont_name= (EditText) findViewById(R.id.cont_name);
        pwd1= (EditText) findViewById(R.id.pwd1);
        back= (ImageView) findViewById(R.id.back);
        title_text= (TextView) findViewById(R.id.title_text);
        title_text.setText("注册账户");
        mForward.setVisibility(View.VISIBLE);
        mForward.setBackground(getResources().getDrawable(R.drawable.pic_qrcode));
        mFilterText.setVisibility(View.VISIBLE);
        mFilterText.setText("扫一扫");
        //fancilty.setEnabled(false);


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){

            case R.id.back:
                //返回登录
                goToLoin();
            break;

            case R.id.validate:
                //请求识别验证码
                reqIdentifyCode();
                break;

            case R.id.register:
                //点击注册
                register();
                break;
            case R.id.forward:
                //扫一扫
                Intent intent = new Intent(RegisterAty.this,CaptureActivity.class);
                startActivityForResult(intent, REQUEST_CODE_SCAN);
                break;
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 扫描二维码/条码回传
        if (requestCode == REQUEST_CODE_SCAN && resultCode == RESULT_OK) {
            if (data != null) {
                String content = data.getStringExtra(DECODED_CONTENT_KEY);
                Bitmap bitmap = data.getParcelableExtra(DECODED_BITMAP_KEY);
                fancilty.setText(content);
            }
        }
    }
    private void register() {

        String pawd = getPasswod();
        String okPawd = getOkPawd();
        if (!PhoneUtils.isMobileNO(getPhone())) {
            ToastUtil.getInstance().toast("手机号码不正确");
            return;
        }

        if (TextUtils.isEmpty(getPhone())){
            ToastUtil.getInstance().toast("请输入手机号");
            return;
        }
        if(TextUtils.isEmpty(getFaclity())){
            ToastUtil.getInstance().toast("请输入设备号");
            return;
        }
        if (TextUtils.isEmpty(getverifyCode())||getverifyCode().length()<4||!getverifyCode().equals(rad)){
            ToastUtil.getInstance().toast("验证码不正确");return;
        }
        if (TextUtils.isEmpty(getOkPawd())||TextUtils.isEmpty(getPasswod())){
            ToastUtil.getInstance().toast("请输入密码");return;
        }

        else if(pawd.length()<6||okPawd.length()<6){
            ToastUtil.getInstance().toast("密码长度不能少于6位数");
            return;
        }
        //判断输入的两次密码  与服务器返回的验证码是否一致
//        if (pawd.equals(okPawd)&&getverifyCode().equals(0)){
        if (pawd.equals(okPawd)){
            RequestParams params = new RequestParams.Builder()
                    .putParam("mobile", getPhone())
                    .putParam("password", MD5Util.MD5Encode(getOkPawd()))
                    .putParam("imei", getFaclity())
                    .putParam("address", getAddress())
                    .build();
        //开始请求发送数据到服务器服务器
            RequestQueue requestQueue = Volley.newRequestQueue(this);
            String url = Urls.getRegister();//回去api路径

            RequestUtil.requestData(requestQueue,
                    IConstants.REGISTER,
                    url,
                    RM.GET,
                    RequestBean.class,
                    params,
                    this);
        }else {
            ToastUtil.getInstance().toast("两次密码不正确");
            return;
        }

    }

    /**
     * 获取设备id
     * MD5加密
     */
//    private String getDiviceId() {
//        TelephonyManager TelephonyMgr = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
//        return MD5Util.MD5Encode(TelephonyMgr.getDeviceId());
//    }


    @Override
    public void requestSuccess(RequestBean bean, Config config) {
        LogUtil.d("requestSuccess");
        if (bean.getStatusCode()==1){
            ToastUtil.getInstance().toast("您的账号已注册");
            return;
        }
                //注册成功
        ToastUtil.getInstance().toast("注册成功");
        goToLoin();

        
    }

    @Override
    public void requestFail(RequestBean bean, Config config) {
        LogUtil.d("requestFail");

    }

    @Override
    public void requestTokenInvalid(String requestTag, Config config) {
        LogUtil.d("requestTokenInvalid");

    }


    private String getOkPawd() {
        return pwd1.getText().toString().trim();
    }

    private String getPasswod() {
       return cont_name.getText().toString().trim();
    }

    private String getverifyCode() {
        return val.getText().toString().trim();
    }

    private void reqIdentifyCode() {
        String phone = getPhone();
        if (!PhoneUtils.isMobileNO(phone)) {
            ToastUtil.getInstance().toast("手机号码不正确");
            return;
        }
//        String noncestr = "" + System.currentTimeMillis(); //时间戳
//        String sign = IdentifyUtils.getClientSign(phone, noncestr); //签名
        rad = RandomCode();
        //TODO  下面需要进行网络请求
        volleyGet();
        //请求成功的话加上以下代码
        startColdTime();

    }
    public void volleyGet(){
       // String path= "http://172.16.2.183:8080/CyclingBgTV1/appRepairByself/r.dop?content="+rad;
       // String path= Urls.getTest()+"?content="+rad;

        String mobile=getPhone();
        String path =Urls.getValidate()+mobile+Urls.getValidateContent()+rad+Urls.getValidateElse();
       // String path="https://dx.ipyy.net/smsJson.aspx?action=send&userid=&account=AG00031&password=AG00031523&mobile="+mobile+"&content=您的验证码："+rad+"【塔西】&sendTime=&extno=";
       // String path = Urls.getRepair();18577366673
        StringRequest request = new StringRequest(path, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                    LogUtil.e(s);
                 //   ToastUtil.getInstance().toast(s);
            }
        },null);
        queue.add(request);
    }
    private int timeC = 0;
    private void startColdTime() {
        timeC = 60;
        coldTimeing();
    }

    private void coldTimeing() {
        if (validate == null)
            return;
        setColdTime(timeC);
        if (timeC > 0) {
            validate.postDelayed(new Runnable() {
                @Override
                public void run() {
                    timeC--;
                    coldTimeing();
                }
            }, 1000);
        }
    }

    /**
     * @param num 倒计时时间, 如果小于等于0, 显示重新发送
     */
    private void setColdTime(int num) {
        if (validate == null) {
            return;
        }
        validate.setEnabled(num <= 0);
        if (num > 0) {
            validate.setText(num + "s");
        } else {
            validate.setText(R.string.str_register_resend);
        }
    }

    private String getPhone() {
        return mobile.getText().toString().trim();
    }
    private String getFaclity(){
        return fancilty.getText().toString().trim();
    }
    private String getAddress(){
        return provinceSpinner.getSelectedItem().toString()+"省"+citySpinner.getSelectedItem().toString()+"市";
    }
    private void goToLoin() {
        Intent intent = new Intent(RegisterAty.this, LoginAty.class);
        startActivity(intent);
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.reset(this);
    }
    private String RandomCode(){
        String str="0123456789";
        StringBuilder sb=new StringBuilder(4);
        for(int i=0;i<4;i++)
        {
            char ch=str.charAt(new Random().nextInt(str.length()));
            sb.append(ch);
        }
        return sb.toString();
    }


}
